import subprocess

import requests
import re
import pprint   # 格式化输出

head = {
    'referer': 'https://search.bilibili.com/',
    'user-agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/99.0.4844.51 Safari/537.36'
}

def get_response(html_url):
    """发送请求函数"""
    resp = requests.get(url=html_url, headers=head)
    return resp



def get_video_info(html_url):
    """获取视频标题 / CID / session"""

    resp = get_response(html_url)
    cid = re.findall('"cid":(\d+),', resp.text)[0]
    session = re.findall('"session":"(.*?)"', resp.text)[0]
    title = re.findall('<h1 title="(.*?)" class="video-title tit">', resp.text)[0].replace(' ', '')
    # print(cid, session, title)
    video_info = [cid, session, title]
    return video_info


def get_video_content(cid, session, bv_id):
    index_url = 'https://api.bilibili.com/x/player/playurl'
    data = {
        'cid' : cid,
        'qn' : '0',
        'type' : '',
        'otvpe' : 'json',
        'fourk' : '1',
        'bvid' : bv_id,
        'fnver' : '0',
        'fnval' : '976',
        'session' : session
    }

    json_data = requests.get(index_url, params=data, headers=head).json()
    audio_url = json_data['data']['dash']['audio'][0]['baseUrl']
    video_url = json_data['data']['dash']['video'][0]['baseUrl']
    # print(audio_url, vidoe_url)
    # pprint.pprint(json_data)

    video_content = [audio_url, video_url]
    return video_content


def save(titel, audio_url, video_url):
    """保存数据"""
    audio_content = get_response(audio_url).content
    video_content = get_response(video_url).content
    with open(titel + '.mp3' , mode='wb') as f:
        f.write(audio_content)
    with open(titel + '.mp4', mode='wb') as f:
        f.write(video_content)

    # print(titel, '保存完成')

def merge_data(video_name):
    '''数据的合并'''
    # 使用正则表达式将标题当中的所有标点符号替换为空，防止执行ffmpeg合并视频和音频时输出视频失败
    video_name = re.sub('\W+', '', video_name).replace("_", '')
    print('视频合成开始：', video_name)
    COMMAND = f'ffmpeg -i {video_name}.mp4 -i {video_name}.mp3 -c:v copy -c:a aac -strict experimental {video_name}out.mp4 '
    subprocess.run(COMMAND, shell=True)
    print('视频合成结束：', video_name)

def mian(bv_id):
    """主函数"""
    url = f'https://www.bilibili.com/video/{bv_id}'
    video_info = get_video_info(url)
    video_content = get_video_content(video_info[0], video_info[1], bv_id)
    save(video_info[2], video_content[0], video_content[1])
    merge_data(video_info[2])





bv= input("请输入你要下载视频的BV号：")
mian(bv)


# cid = '112274088'
# session = 'effd55577fddc81c97a8571a444202ac'
# bv = 'BV1p4411d7og'
# get_video_content(cid, session, bv)



# url = 'https://www.bilibili.com/video/BV1p4411d7og'
# get_cideo_info(url)


















